package main.编程题;

/**
 * @author tmh
 * @date 2024/8/1 18:42
 * @description
 */
public class T线程交替打印1A2B3C {
    private static final Object lock = new Object();
    //定义一个共享变量
    private static boolean isNumber = true;

    public static void main(String[] args) {
        Thread digitThread = new Thread(()->{
            synchronized (lock){
                    for (int i  =1;i<=3;i++){
                        while (!isNumber){
                            //这个是字母的逻辑，那就调用wait方法进行阻塞
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        //这个是数字的逻辑，就是直接打印
                        System.out.print(i);
                        isNumber=!isNumber;
                        //唤醒打印字母的线程
                        lock.notify();
                    }
            }
        });
        Thread letterThread = new Thread(()->{
            synchronized (lock){
                for (char c='A';c<='C';c++){
                    while (isNumber){
                        //阻塞
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    //打印字母的逻辑
                    System.out.print(c);
                    isNumber=!isNumber;
                    //唤醒打印数字的线程
                    lock.notify();
                }
            }
        });
        digitThread.start();
        letterThread.start();
    }

}
